"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.createCache = void 0;
class AbstractCache {
  /** 特定前缀，作为筛分的命名空间 */
  keyPrefix = '';
  constructor(keyPrefix) {
    this.keyPrefix = keyPrefix;
  }
  getPrefixedKey(key) {
    return `${this.keyPrefix}::${key}`;
  }
}

/** 内存缓存 */
class MemoryCache extends AbstractCache {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  data = {};

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  set(key, value, options) {
    const prefixedKey = this.getPrefixedKey(key);
    this.data[prefixedKey] = {
      value,
      expire: options?.expire ? new Date().getTime() + options?.expire : undefined
    };
  }
  get(key) {
    const prefixedKey = this.getPrefixedKey(key);
    const cachedData = this.data[prefixedKey];
    if (cachedData?.expire && cachedData?.expire < new Date().getTime()) {
      return undefined;
    }
    return cachedData?.value;
  }
  clear(key) {
    if (key) {
      const prefixedKey = this.getPrefixedKey(key);
      delete this.data[prefixedKey];
      return;
    }
    this.data = {};
  }
  length() {
    return Object.keys(this.data).length;
  }
}
class StorageCache extends AbstractCache {
  storage;

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  set(key, value, options) {
    const prefixedKey = this.getPrefixedKey(key);
    this.storage?.setItem(prefixedKey, JSON.stringify({
      value,
      expire: options?.expire ? new Date().getTime() + options?.expire : undefined
    }));
  }
  get(key) {
    const prefixedKey = this.getPrefixedKey(key);
    const storagedVal = this.storage?.getItem(prefixedKey);
    if (!storagedVal) return undefined;
    const cachedData = JSON.parse(storagedVal);
    if (cachedData?.expire && cachedData?.expire < new Date().getTime()) {
      return undefined;
    }
    return cachedData.value;
  }
  clear(key) {
    if (key) {
      const prefixedKey = this.getPrefixedKey(key);
      this.storage?.removeItem(prefixedKey);
      return;
    }
    this.storage?.clear();
  }
  length() {
    return this.storage?.length ?? 0;
  }
}

/** LocalStorage 缓存 */
class LocalStorageCache extends StorageCache {
  storage = localStorage;
}

/** SessionStorage 缓存 */
class SessionStorageCache extends StorageCache {
  storage = sessionStorage;
}

/** 创建缓存 */
const createCache = options => {
  const {
    type = 'memory',
    keyPrefix = ''
  } = options ?? {};
  if (type === 'localStorage') {
    return new LocalStorageCache(keyPrefix);
  } else if (type === 'sessionStorage') {
    return new SessionStorageCache(keyPrefix);
  }
  return new MemoryCache(keyPrefix);
};
exports.createCache = createCache;